package org.springframework.amqp.tutorials.rabbitmq_topics.mq;

import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.util.StopWatch;

import java.util.concurrent.TimeUnit;

public class Tut5Receiver {
    @RabbitListener(queues = "#{autoDetectQueue1.name}")
    public void receive1(String in) throws InterruptedException {
        receive(in, 1);
    }

    @RabbitListener(queues = "#{autoDetectQueue2.name}")
    public void receive2(String in) throws InterruptedException {
        receive(in, 2);
    }

    private void receive(String in, int receiver) throws InterruptedException {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        System.out.println("instance " + receiver +
                " [x] receive message: '" + in + "'");
        doWork(in);
        stopWatch.stop();
        System.out.println("instance " + receiver +
                " [x] Done in " + stopWatch.getTotalTimeSeconds() + " s");
    }

    private void doWork(String in) throws InterruptedException {
        for (char ch : in.toCharArray()) {
            if (ch == '.') {
                TimeUnit.SECONDS.sleep(1);
            }
        }
    }
}
